package jsp;

import entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

/**
 * @Author:石小俊
 * @Date:2022/12/14 10:31
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String path = request.getServletPath();
        if("/login.user".equals(path)){
            login(request,response);
        }
        if("/logout.user".equals(path)){
            logout(request,response);
        }
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath()+"/session/main.jsp");
    }
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 验证码
        // 获取用户输入的验证码
        String code = request.getParameter("code");
        // 获取验证码图片的内容
        String image = (String) request.getSession().getAttribute("code");
        if(!code.equals(image)){
            request.setAttribute("loginMsg","验证码不正确");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
            return;
        }
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","");
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .append(" and password = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            while(rs.next()){
                // 用户名与密码正确
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));

                // 登录成功之后,将用户信息保存到session中
                request.getSession().setAttribute("user",user);
                // 页面跳转到主页,session支持跨请求传递数据
                // 登录成功之后跳转到主页,主页功能与当前业务无关,此时一般也会使用重定向来实现
                response.sendRedirect(request.getContextPath()+"/session/main.jsp");
                return;
            }
            conn.commit();
            request.setAttribute("loginMsg","用户名或密码错误");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            request.setAttribute("loginMsg","服务器内部异常");
            request.getRequestDispatcher("/session/login.jsp").forward(request,response);
        } finally {
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
